import { ApiCall } from 'tsrpc'
import { ReqImportConfigs, ResImportConfigs } from '../shared/api_config_editor/PtlImportConfigs'

export default async function (call: ApiCall<ReqImportConfigs, ResImportConfigs>) {
    try {
        const { type, data, options } = call.req
        
        let imported = 0
        let skipped = 0
        const errors: string[] = []
        
        // 验证导入数据
        if (!Array.isArray(data)) {
            call.error('导入数据必须是数组格式')
            return
        }
        
        // 读取现有配置
        const fs = require('fs')
        const path = require('path')
        const configDir = path.resolve(__dirname, '../core/config')
        
        let existingConfigs: any[] = []
        const configFile = path.join(configDir, `${type}_configs.json`)
        
        if (fs.existsSync(configFile)) {
            try {
                const content = fs.readFileSync(configFile, 'utf-8')
                const existingData = JSON.parse(content)
                existingConfigs = Array.isArray(existingData) ? existingData : [existingData]
            } catch (error) {
                console.warn(`Failed to read existing config file: ${error}`)
            }
        }
        
        // 创建ID映射以便查重
        const existingIds = new Set(existingConfigs.map(config => 
            config.id || config.skillId || config.name
        ))
        
        // 处理导入数据
        for (const item of data) {
            try {
                const itemId = item.id || item.skillId || item.name
                
                if (!itemId) {
                    errors.push('配置项缺少唯一标识符')
                    skipped++
                    continue
                }
                
                // 检查是否重复
                if (existingIds.has(itemId) && !options.merge) {
                    skipped++
                    continue
                }
                
                // 验证配置项
                if (options.validate) {
                    const validationResult = validateConfigItem(type, item)
                    if (!validationResult.isValid) {
                        errors.push(`${itemId}: ${validationResult.errors.join(', ')}`)
                        skipped++
                        continue
                    }
                }
                
                // 添加或更新配置
                if (existingIds.has(itemId) && options.merge) {
                    // 更新现有配置
                    const index = existingConfigs.findIndex(config => 
                        (config.id || config.skillId || config.name) === itemId
                    )
                    if (index !== -1) {
                        existingConfigs[index] = { ...existingConfigs[index], ...item }
                    }
                } else {
                    // 添加新配置
                    existingConfigs.push(item)
                    existingIds.add(itemId)
                }
                
                imported++
                
            } catch (error) {
                errors.push(`处理配置项失败: ${(error as any).message}`)
                skipped++
            }
        }
        
        // 保存配置
        if (imported > 0) {
            // 创建备份
            if (options.backup && fs.existsSync(configFile)) {
                const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
                const backupDir = path.resolve(__dirname, '../backups')
                
                if (!fs.existsSync(backupDir)) {
                    fs.mkdirSync(backupDir, { recursive: true })
                }
                
                const backupFile = path.join(backupDir, `${type}_${timestamp}.json`)
                fs.copyFileSync(configFile, backupFile)
            }
            
            // 确保配置目录存在
            if (!fs.existsSync(configDir)) {
                fs.mkdirSync(configDir, { recursive: true })
            }
            
            // 保存更新后的配置
            fs.writeFileSync(configFile, JSON.stringify(existingConfigs, null, 2))
            
            // 重新加载配置
            try {
                const { configManager } = require('../config/ConfigManager')
                await configManager.reload()
            } catch (error) {
                console.warn('Failed to reload config manager:', error)
            }
        }
        
        call.succ({
            data: {
                imported,
                skipped,
                errors
            }
        })
        
    } catch (error) {
        console.error('Failed to import configs:', error)
        call.error('导入配置失败', {
            errors: [(error as any).message]
        })
    }
}

/**
 * 验证配置项
 */
function validateConfigItem(type: string, item: any): { isValid: boolean, errors: string[] } {
    const errors: string[] = []
    
    switch (type) {
        case 'equipment':
            if (!item.id) errors.push('装备ID不能为空')
            if (!item.name) errors.push('装备名称不能为空')
            if (!item.sys) errors.push('装备体系不能为空')
            if (!item.type) errors.push('装备类型不能为空')
            if (!item.job) errors.push('装备职业不能为空')
            if (!item.solt) errors.push('装备部位不能为空')
            
            if (item.quality) {
                if (typeof item.quality.min !== 'number' || typeof item.quality.max !== 'number') {
                    errors.push('品质范围必须是数字')
                }
                if (item.quality.min > item.quality.max) {
                    errors.push('品质最小值不能大于最大值')
                }
            }
            break
            
        case 'skill':
            if (!item.skillId && !item.id) errors.push('技能ID不能为空')
            if (!item.name) errors.push('技能名称不能为空')
            
            if (item.maxLevel && (typeof item.maxLevel !== 'number' || item.maxLevel < 1)) {
                errors.push('技能最高等级必须是大于0的数字')
            }
            
            if (item.cooldown && (typeof item.cooldown !== 'number' || item.cooldown < 0)) {
                errors.push('技能冷却时间必须是非负数字')
            }
            break
            
        default:
            if (!item.id && !item.name) {
                errors.push('配置必须包含id或name字段')
            }
    }
    
    return {
        isValid: errors.length === 0,
        errors
    }
}
